package com.qdaily.ui.ui.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextPaint;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.webkit.WebSettings;
import android.widget.*;

import com.qdaily.supportlibrary.request.JsonData;
import com.qdaily.supportlibrary.util.*;
import com.qdaily.supportlibrary.views.PageLoadingView;
import com.qdaily.ui.QDBaseActivity;
import com.qdaily.ui.QDBaseFragment;
import com.qdaily.ui.R;
import com.qdaily.ui.controller.ActivityController;
import com.qdaily.ui.data.DataBase.ReadDAO;
import com.qdaily.ui.data.EventModel.EventCOPChange;
import com.qdaily.ui.data.EventModel.EventQDWebViewLoadComplete;
import com.qdaily.ui.data.QDConfigConstants;
import com.qdaily.ui.data.QDConfigManager;
import com.qdaily.ui.net.NetConfigs;
import com.qdaily.ui.net.QDEnum;
import com.qdaily.ui.net.entity.ArticleInfoEntity;
import com.qdaily.ui.net.model.ArticleInfo;
import com.qdaily.ui.net.model.ArticleMeta;
import com.qdaily.ui.net.model.ArticleMetaCategory;
import com.qdaily.ui.net.model.ArticleMetaTag;
import com.qdaily.ui.ui.ShowWebImageActivity;
import com.qdaily.ui.ui.adapter.CommentsAdapter;
import com.qdaily.ui.ui.views.ArticleInfoController;
import com.qdaily.ui.ui.views.CommentController;
import com.qdaily.ui.ui.views.InputBar;
import com.qdaily.ui.ui.views.QDCommentView;
import com.qdaily.ui.ui.views.QDRefreshCommentView;
import com.qdaily.ui.ui.views.QDWebView.QDArticleWebChromeClient;
import com.qdaily.ui.ui.views.QDWebView.QDArticleWebView;
import com.qdaily.ui.ui.views.QDWebView.QDArticleWebViewClient;
import com.qdaily.ui.ui.views.QDWebView.WebViewJavascriptBridge;
import com.qdaily.ui.util.QDRegUtil;
import com.squareup.otto.Subscribe;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by song on 15/5/12.
 */
public class ArticleDetailFragment extends QDBaseFragment implements View.OnClickListener {

    private QDArticleWebView mWebView;
    private ArticleInfoController articleInfoController;

    //comments listview
    private QDCommentView mCommentView;
    private CommentsAdapter commentsAdapter;
    private CommentController commentController;
    private InputBar inputBar;

    private View titleBar;
    private LinearLayout article_titlebar_taglayout;
    private ImageView titlebarIcon;
    private TextView titlebarText;

    private boolean isLoading;

    private ArticleMeta articleMeta;
    private ArticleInfo articleInfo;

    private QDBaseActivity acticity;

    private final String QDTAG = "ArticleDetailFragment";

    private View rootView;
    private PageLoadingView loadingView;
    private FrameLayout contentLayout;

    public final static String KEY_ARTICLEMETA = "articleMeta";
    public final static String KEY_ARTICLEINFO = "articleInfo";
    private boolean isHideComment; // 卡片不显示下面的东西

    public QDArticleWebView getmWebView() {
        return mWebView;
    }

    @Override
    public void setArguments(Bundle args) {
        super.setArguments(args);
        articleMeta = args.getParcelable(KEY_ARTICLEMETA);
        articleInfo = args.getParcelable(KEY_ARTICLEINFO);
        if (articleMeta == null && articleInfo != null) {
            articleMeta = new ArticleMeta();
            articleMeta.setPost(articleInfo.getPost());
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.view_article_detail;
    }

    @Override
    protected void setupViews(View view) {
        rootView = view;
        mCommentView = (QDCommentView) view.findViewById(R.id.articleCommentView);
    }

    @Override
    protected void setupData() {
        if (getActivity() instanceof QDBaseActivity) {
            acticity = (QDBaseActivity) getActivity();
        } else {
            QLog.e(QDTAG, "getActivity() instanceof QDBaseActivity is NO");
            return;
        }
        if (articleMeta == null) {
            acticity.displayToast("访问出错，请稍后重试");
            QLog.e(QDTAG, "ArticleMeta传送失败");
            acticity.finish();
            return;
        }
        isHideComment = articleMeta.getPost().getGenre() == 12;

        loadViewShow();

        inputBar = new InputBar(acticity, rootView, R.id.article_inputbar, true);
        inputBar.setInputBarType(articleMeta.getPost().getId(), QDEnum.DetailEnum.ARTICLE);
        articleInfoController = new ArticleInfoController(acticity);

        int articleId = articleMeta.getPost().getId();
        this.commentsAdapter = new CommentsAdapter(acticity, mCommentView);
        commentController = new CommentController(acticity, commentsAdapter, inputBar, articleId, QDEnum.DetailEnum.ARTICLE);

        configWebView();

        mCommentView.setVerticalScrollBarEnabled(false);

//        requestArticleInfo();
    }

    /**
    //以下用于计算标题栏，废弃，改为Webview自己处理
    private int tagLayoutWidth;

    private void configTitleBar(View view) {
        titleBar = view.findViewById(R.id.article_titlebar);
        if (articleMeta.getPost().getPage_style() == 1) {
            titleBar.setVisibility(View.GONE);
            return;
        }
        article_titlebar_taglayout = (LinearLayout) titleBar.findViewById(R.id.article_titlebar_taglayout);
        titlebarIcon = (ImageView) view.findViewById(R.id.article_titlebar_icon);
        titlebarText = (TextView) view.findViewById(R.id.article_titlebar_title);
        ImageUtil.getInstance().displayAvatorImage(articleMeta.getPost().getCategory().getImage(), titlebarIcon);
        titlebarText.setText(articleMeta.getPost().getCategory().getTitle());
        article_titlebar_taglayout.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View view, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7) {
                int curTagLayoutWidth = article_titlebar_taglayout.getMeasuredWidth();
                if (curTagLayoutWidth != tagLayoutWidth) {
                    tagLayoutWidth = curTagLayoutWidth;
                    configTagLayout();
                }
            }
        });
    }

    private void configTagLayout() {
        if (articleMeta.getPost().getPage_style() == 1 || article_titlebar_taglayout == null)
            return;
        article_titlebar_taglayout.removeAllViews();
        int curWidth = tagLayoutWidth;
        if (curWidth == 0)
            return;
        if (articleInfo == null || articleInfo.getPost() == null || articleInfo.getPost().getTag() == null)
            return;

        if (curWidth > LocalDisplay.SCREEN_WIDTH_PIXELS / 2) {
            curWidth = LocalDisplay.SCREEN_WIDTH_PIXELS / 2;
        }

        int padding = getResources().getDimensionPixelOffset(R.dimen.article_title_tag_padding);
        int marginRight = getResources().getDimensionPixelOffset(R.dimen.article_title_tag_marginright);
        int textsize = getResources().getDimensionPixelOffset(R.dimen.article_title_tag_textsize);
        padding = 5;
        marginRight = 10;
        textsize = 15;
        for (ArticleMetaTag tag : articleInfo.getPost().getTag()) {
            Rect bounds = new Rect();
            TextPaint paint;
            TextView tagTextView = new TextView(acticity);

            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(0, 0, marginRight, 0);
            tagTextView.setLayoutParams(lp);

            tagTextView.setGravity(Gravity.CENTER);
            tagTextView.setPadding(padding, padding, padding, padding);
            tagTextView.setTextColor(getResources().getColor(R.color.white));
            tagTextView.setTextSize(textsize);
            tagTextView.setBackgroundColor(getResources().getColor(R.color.gray));

            paint = tagTextView.getPaint();
            paint.getTextBounds(tag.getTitle(), 0, tag.getTitle().length(), bounds);
            int width = bounds.width();
            QLog.w("configTagLayout", "tagTextView width:" + width);

            if (curWidth > width + LocalDisplay.designedDP2px(marginRight + padding * 2)) {
                tagTextView.setTag(tag);
                tagTextView.setText(tag.getTitle());
                tagTextView.setOnClickListener(this);
                article_titlebar_taglayout.addView(tagTextView);
                curWidth -= width + LocalDisplay.designedDP2px(marginRight);
            } else {
                break;
            }
        }
    }

    private boolean titleBarHide = false;

    private void setTitleBarHide(boolean hide) {
        if (titleBar == null)
            return;
        if (titleBarHide != hide) {
            titleBarHide = hide;
            if (hide) {
                TranslateAnimation animation = new TranslateAnimation(0, 0, 0, -titleBar.getMeasuredHeight());
                animation.setDuration(500);
                titleBar.setAnimation(animation);

                animation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                        titleBar.setY(0);
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        titleBar.setY(-titleBar.getMeasuredHeight());
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
                animation.start();
            } else {
                TranslateAnimation animation = new TranslateAnimation(0, 0, -titleBar.getMeasuredHeight(), 0);
                animation.setDuration(500);
                titleBar.setAnimation(animation);
                animation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                        titleBar.setY(-titleBar.getMeasuredHeight());
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        titleBar.setY(0);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
                animation.start();
            }
        }
    }
**/

    private void configWebView() {
        mWebView = new QDArticleWebView(acticity);
        mWebView.getSettings().setJavaScriptEnabled(true);
//        mWebView.getSettings().setAppCacheEnabled(false);
//        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.setWebChromeClient(new QDArticleWebChromeClient());
        QDArticleWebViewClient webViewClient = new QDArticleWebViewClient(acticity);
        webViewClient.setmWebView(mWebView);

        mWebView.setWebViewClient(webViewClient);
        mWebView.configJavascriptBidge(acticity);
        mWebView.getBridge().registerHandler(QDArticleWebView.HandlerKey_ChildComment, new WebViewJavascriptBridge.WVJBHandler() {
            @Override
            public void handle(String data, WebViewJavascriptBridge.WVJBResponseCallback jsCallback) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    int parent_id = jsonObject.getInt("parent_id");
                    commentController.onParentCommentClick(parent_id);
                } catch (JSONException e) {
                    QLog.e(QDTAG, "js请求子评论JSON解析错误，data=" + data);
                }
            }
        });
        mWebView.getBridge().registerHandler(QDArticleWebView.HandlerKey_ChildPraise, new WebViewJavascriptBridge.WVJBHandler() {
            @Override
            public void handle(String data, WebViewJavascriptBridge.WVJBResponseCallback jsCallback) {
                QLog.w(QDTAG, "js请求子点赞，data=" + data);
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    int parent_id = jsonObject.getInt("id");
                    commentController.onParentLikedClick(parent_id);
                } catch (JSONException e) {
                    QLog.e(QDTAG, "js请求子点赞JSON解析错误，data=" + data);
                }
            }
        });
        mWebView.getBridge().registerHandler(QDArticleWebView.HandlerKey_PicPreview, new WebViewJavascriptBridge.WVJBHandler() {
            @Override
            public void handle(String data, WebViewJavascriptBridge.WVJBResponseCallback jsCallback) {
                QLog.w(QDTAG, "js请求看图，data=" + data);
                try {
                    String host = QDRegUtil.getQArticleHost(mWebView.getOriginalUrl());
                    JSONObject jsonObject = new JSONObject(data);
                    int cur = jsonObject.getInt("cur");
                    JSONArray jsonArray = jsonObject.getJSONArray("pics");
                    ArrayList<String> datas = new ArrayList<>();
                    int count = jsonArray.length();
                    for (int i = 0; i < count; i++) {
                        String url = jsonArray.getString(i);
                        if (url.startsWith("http")) {
                            datas.add(url);
                        } else {
                            if (url.startsWith("/")) {
                                datas.add(host + url);
                            } else {
                                datas.add(host + "/" + url);
                            }
                        }
                    }
                    Intent toImageActicity = new Intent(acticity, ShowWebImageActivity.class);
                    toImageActicity.putExtra(ShowWebImageActivity.EXTRA_SHOW_WEB_IMAGE_KEY, datas);
                    toImageActicity.putExtra(ShowWebImageActivity.EXTRA_SHOW_WEB_IMAGE_KEY_POSTION, cur);
                    toImageActicity.putExtra(QDBaseActivity.KEY_ActivityAnim, QDEnum.EActivityAnim.Fade);
                    acticity.startActivity(toImageActicity);
                } catch (JSONException e) {
                    QLog.e(QDTAG, "js请求看图JSON解析错误，data=" + data);
                }
            }
        });

        mWebView.getBridge().registerHandler(QDArticleWebView.HandlerKey_PageReady, new WebViewJavascriptBridge.WVJBHandler() {
            @Override
            public void handle(String data, WebViewJavascriptBridge.WVJBResponseCallback jsCallback) {
                QLog.w(QDTAG, "js请求-页面加载完成");
                receiveWebViewLoadComplete(new EventQDWebViewLoadComplete(mWebView));
                int fontSize = QDConfigManager.getInstance().getInt(QDConfigConstants.KEY_FONT_SIZE, QDEnum.EFontSize.MIDDLE.value);
                if (fontSize != QDEnum.EFontSize.MIDDLE.value) {
                    String size = "l";
                    if (fontSize == QDEnum.EFontSize.SMALL.value) {
                        size = "s";
                    }
                    Map<String, String> stringMap = new HashMap<String, String>();
                    stringMap.put("size", size);
                    mWebView.getBridge().callHandler(QDArticleWebView.CallBackKey_SetFont, stringMap);
                }
            }
        });

        mWebView.getBridge().registerHandler(QDArticleWebView.HandlerKey_GoPage, new WebViewJavascriptBridge.WVJBHandler() {
            @Override
            public void handle(String data, WebViewJavascriptBridge.WVJBResponseCallback jsCallback) {
                QLog.w(QDTAG, "js请求GoToPage，data=" + data);
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    String type = jsonObject.getString("type");
                    JSONObject params = jsonObject.getJSONObject("params");
                    if (type.equals(QDEnum.JSGoToPageEnum.CATEGORY.value)) {
                        ArticleMetaCategory category = new ArticleMetaCategory();
                        category.setId(params.getInt("id"));
                        category.setTitle(params.getString("title"));
                        ActivityController.DisplayCategory(acticity, category);
                    } else if (type.equals(QDEnum.JSGoToPageEnum.TAG.value)) {
                        ArticleMetaTag tag = new ArticleMetaTag();
                        tag.setId(params.getInt("id"));
                        tag.setTitle(params.getString("title"));
                        ActivityController.DisplayTag(acticity, tag);
                    }
                } catch (JSONException e) {
                    QLog.e(QDTAG, "js请求GoToPage JSON解析错误，data=" + data);
                }
            }
        });

        if (articleMeta.getPost().getGenre() == 12) //卡片
        {
            commentController.setOnCommentSuccessListener(new CommentController.OnCommentSuccessListener() {
                @Override
                public void callback(String data) {
                    QLog.w(QDTAG, "js请求子评论成功返回数据，data=" + data);
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        mWebView.getBridge().callHandler(QDArticleWebView.CallBackKey_ChildCommentResult, jsonObject.get("response"));
                    } catch (JSONException e) {
                        QLog.e(QDTAG, "js请求子评论成功返回数据JSON解析错误，data=" + data);
                    }
                }
            });

            commentController.setOnPraiseSuccessListener(new CommentController.OnPraiseSuccessListener() {
                @Override
                public void callback(String data) {
                    QLog.w(QDTAG, "js请求子点赞成功返回数据，data=" + data);
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        mWebView.getBridge().callHandler(QDArticleWebView.CallBackKey_ChildPraiseResult, jsonObject.get("response"));
                    } catch (JSONException e) {
                        QLog.e(QDTAG, "js请求子点赞成功返回数据JSON解析错误，data=" + data);
                    }
                }
            });
        }

        { //默认先把webview挂在和listview同一级下
            mWebView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            contentLayout = (FrameLayout) rootView.findViewById(R.id.content_framelayout);
            if (isHideComment)
            {
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) contentLayout.getLayoutParams();
                lp.setMargins(0, 0, 0, 0);
                contentLayout.setLayoutParams(lp);
            }
            contentLayout.addView(mWebView);
        }

        mWebView.loadArticle(articleMeta.getPost().getAppview());
    }

    //页面加载第一步，调到这里表示网页出来了，可以继续搞了
    private boolean isReceiveWebViewLoadComplete = false;//可能会收到多次，只处理一次
    @Subscribe
    public void receiveWebViewLoadComplete(EventQDWebViewLoadComplete event) {
        if (event.getWebView() == mWebView) {
            if (!isReceiveWebViewLoadComplete )
            {
                //TODO 记录文章已读
                ReadDAO.getInstance().read(articleMeta.getPost().getId(), QDEnum.DetailEnum.ARTICLE.value);
                isReceiveWebViewLoadComplete = true;
                loadViewHide();
                if (!isHideComment) //隐藏的都挂在平级view里了
                {
                    contentLayout.removeView(mWebView);
                    mWebView.setLayoutParams(new AbsListView.LayoutParams(LocalDisplay.SCREEN_WIDTH_PIXELS, AbsListView.LayoutParams.WRAP_CONTENT));
                    mCommentView.addHeaderView(mWebView);
                }
                requestArticleInfo();
            }
            else
            {
//
//                mWebView.reload();
            }


            QLog.w(QDTAG, "receiveWebViewLoadComplete");
        }
    }


    //页面加载第二步开始，调到这里表示作者和评论点赞数出来了，可以继续加评论了
    //按顺序loading
    private void requestArticleInfo() {
        if (articleInfo == null) {
            getRequestManager().requestArticleInfo(articleMeta.getPost().getId());
        } else {
            configArticleInfo();
        }
    }

    private void configArticleInfo()
    {
        if (articleInfo != null) {
            commentController.setArticleInfoShare(articleInfo.getShare());
            inputBar.setPraiseCount(articleInfo.getPost().getPraise_count());
            inputBar.setCommentCount(articleInfo.getPost().getComment_count());
            if (!isHideComment) {
                View headView = articleInfoController.getArticleInfoView(articleInfo);
                mCommentView.addHeaderView(headView);
                mCommentView.setAdapter(commentsAdapter);
                commentController.loadData(mCommentView);
            }
        }
    }

    @Override
    protected void onRequestCallBack(NetUtil.NetParams params, JsonData response) {
        super.onRequestCallBack(params, response);
        isLoading = false;
        if (params instanceof NetConfigs.RequestArticleInfo) {
            ArticleInfoEntity articleInfoEntity = QDJsonUtil.Json2Object(response.toString(), ArticleInfoEntity.class);
            articleInfo = articleInfoEntity.getResponse();
            configArticleInfo();
        }
    }

    @Override
    protected void onRequestErrorCallBack(NetUtil.NetParams params, Object response) {
        QLog.w(QDTAG, "onRequestErrorCallBack");
        inputBar.configMinToolbar();
        if (!isHideComment) //调到这里，需要显示出来
        {
            mCommentView.setAdapter(commentsAdapter);
            commentController.loadData(mCommentView);
        }
    }

    @Override
    public void onClick(View view) {
        ArticleMetaTag tag = (ArticleMetaTag) view.getTag();
        ActivityController.DisplayTag(acticity, tag);
    }

    private void initLoadView() {
        if (loadingView == null) {
            loadingView = new PageLoadingView(acticity);
        }
    }

    private long loadingviewShowTime = 0;

    private void loadViewShow() {
        initLoadView();
        if (acticity != null && loadingView != null && !loadingView.isShowing()) {
            loadingView.show();
            loadingviewShowTime = System.currentTimeMillis();
//            new Handler().postDelayed(new Runnable() {
//                public void run() {
//                    loadViewHide();
//                }
//            }, 8000);
        }
    }

    private void loadViewHide() {

        long curTime = System.currentTimeMillis();
        if (loadingviewShowTime != 0 && curTime - loadingviewShowTime < 1500) {
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    loadViewHide();
                }
            }, 1500 - curTime + loadingviewShowTime);
        } else {
            if (acticity != null
                    && !acticity.isFinishing()
                    && loadingView != null
                    && loadingView.isShowing()) {
                loadingView.dismiss();
                loadingView.clear();
                loadingView = null;
            }
        }
    }

    @Subscribe
    public void receiveCOPDataChane(EventCOPChange event) {
        if (event.getType() == QDEnum.DetailEnum.ARTICLE && event.getId() == articleMeta.getPost().getId()) //表示对应我们文章
        {
            if (event.getCommentCount() != -1) {
                inputBar.setCommentCount(event.getCommentCount());
                if (articleMeta.getPost().getGenre() != 12)
                    articleInfoController.setCommentCount(event.getCommentCount());
            }
            if (event.getCopEnum() == QDEnum.COPEnum.ARTICLE) {
                if (event.getPraiseCount() != -1) {
                    inputBar.setPraiseCount(event.getPraiseCount());
                }
            }
        }
    }
}
